﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using System.Timers;
/// <summary>
///Trace 的摘要说明
/// </summary>
namespace EmoneyWeiXinCommon
{
    public class MyTrace
    {
        private string _logAddress;
        private static MyTrace _trace;
        public static int debugMode = 2;//0关闭log记录，1 只记录重要log，2 log全记录。
        public const int IMPORTANT = 1;
        public const int COMMON = 2;
        //private List<string> _list;
        private StringBuilder _list;
        private int _count = 0;

        private StringBuilder _debugList;
        private int _debugCount = 0;
        private Timer _timer;
        private bool _isbusy;
        private bool _is_debugBusy;
        private MyTrace()
        {
            //_list = new List<string>();
            _list = new StringBuilder();
            _debugList = new StringBuilder();
            _logAddress = Config.WeiXin_logAddress;
            if (debugMode == 0) return;
            _timer = new Timer(10000);//实例化Timer类，设置间隔时间为10000毫秒；
            _timer.Elapsed += new ElapsedEventHandler(timerOut);//到达时间的时候执行事件；
            _timer.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；
            _timer.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件；
        }
        private void timerOut(object source, System.Timers.ElapsedEventArgs e)
        {
            flush();
            flush_debug();
        }
        public static MyTrace get()
        {
            if (_trace == null)
            {
                _trace = new MyTrace();
            }
            return _trace;
        }
        public int getlen()
        {
            if (_list != null)
                //return _list.Count;            
                return _count;
            else return 0;
        }
        //public int get_debuglen()
        //{
        //    if (_debugList != null)
        //        //return _list.Count;            
        //        return _debugCount;
        //    else return 0;
        //}
        /// <summary>
        /// 记录一般日志
        /// </summary>
        /// <param name="str"></param>
        public void add(string str)
        {
            //_list.Add(str);
            if (debugMode < COMMON) return;
            _list.Append("[" + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss:fff") + "]--" + str + "--\r\n");
            _count++;
            if (_count > 5000) flush();
        }
        public void add(params string[] strs)
        {
            if (debugMode < COMMON) return;
            string a = "";
            for (int i = 0; i < strs.Length; i++)
            {
                a += "[" + strs[i] + "]";
            }
            _list.Append("[" + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss:fff") + "]--" + a + "\r\n");
            _count++;
            if (_count > 5000) flush();
        }
        public void debug(params string[] strs)
        {
            string a = "";
            for (int i = 0; i < strs.Length; i++)
            {
                a += "[" + strs[i] + "]";
            }
            _debugList.Append("Debug[" + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss:fff") + "]--" + a + "\r\n");
            _debugCount++;
            if (_debugCount > 5000) flush_debug();
        }
        public void add(string str, int level)
        {
            //_list.Add(str);
            if (debugMode < level) return;
            if (level == IMPORTANT)
                _list.Append("/***/[" + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss:fff") + "]--" + str + "--\r\n");
            else
                _list.Append("[" + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss:fff") + "]--" + str + "--\r\n");
            _count++;
            if (_count > 5000) flush();
        }
        public void flush()
        {
            if (_list.Length == 0) return;
            if (!_isbusy)
            {
                _isbusy = true;
                string filename = String.Format("{0:yyyyMMdd}", DateTime.Now) + ".txt";
                StreamWriter sw4 = new StreamWriter(_logAddress + "\\" + filename, true, Encoding.GetEncoding("GB2312"));
                try
                {
                    sw4.Write(_list.ToString());
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    sw4.Close();
                    sw4.Dispose();
                }
                _list.Remove(0, _list.Length);
                _list = new StringBuilder();
                _count = 0;
                _isbusy = false;
            }
        }
        private void flush_debug()
        {
            if (_debugList.Length == 0) return;
            if (!_is_debugBusy)
            {
                _is_debugBusy = true;
                string filename = String.Format("{0:yyyyMMdd}", DateTime.Now) + "_debug" + ".txt";
                StreamWriter sw4 = new StreamWriter(_logAddress + "\\" + filename, true, Encoding.GetEncoding("GB2312"));
                try
                {
                    sw4.Write(_debugList.ToString());
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    sw4.Close();
                    sw4.Dispose();
                }
                _debugList.Remove(0, _debugList.Length);
                _debugList = new StringBuilder();
                _debugCount = 0;
                _is_debugBusy = false;
            }
        }
    }
}